package com.edu.security;


import net.sf.json.JSONObject;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, org.springframework.security.access.AccessDeniedException e) throws IOException, ServletException {
        String header = req.getHeader("X-Requested-With");
        if( header!=null && "XMLHttpRequest".equals(header)){
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(getJson());
        }else {
            String ctxPath = req.getContextPath();
            resp.sendRedirect( ctxPath + "403_error.html");
        }
    }
    private String getJson() {
        JSONObject json = new JSONObject();
        json.put("result","failed");
        json.put("code","403");
        json.put("cause","你没有权限访问资源.");
        return json.toString();
    }


}
